package com.ddd.coze.feature.userlogin


import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.skydoves.chatgpt.core.data.repository.AppUserRepository
import com.skydoves.chatgpt.core.model.network.LoginResponse
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch
import javax.inject.Inject

@HiltViewModel
class UserLoginViewModel @Inject constructor(
  private val userRepository: AppUserRepository
) : ViewModel() {

  private val loginMutableState =
    MutableStateFlow<UiState>(UiState.Nothing)
  val loginState: StateFlow<UiState> = loginMutableState


  var errorMessage: String? = null
    private set

  fun login(username: String, password: String, onSuccess: (LoginResponse) -> Unit) {
    try {
      viewModelScope.launch {
        loginMutableState.value=UiState.Loading
        val response = userRepository.login(username, password)
        if (response != null) {
          onSuccess(response) // 登录成功，调用成功回调
          loginMutableState.value=UiState.Nothing
        } else {
          loginMutableState.value=UiState.Nothing
          errorMessage = "登录失败，请检查用户名和密码" // 设置错误信息
        }
      }
    }catch (e:Exception){
      loginMutableState.value=UiState.Nothing
      println("Error: ${e.localizedMessage}")
    }


  }

}

sealed interface UiState {
  data object Nothing : UiState

  data object Loading : UiState
}

